package com.slf.engine.threads;


import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

import com.slf.engine.common.SysContants;
import com.slf.engine.common.SysContext;
import com.slf.engine.services.IReloadService;
import com.slf.engine.services.IZjzhService;
import com.slf.engine.services.impl.ReloadServiceImpl;
import com.slf.engine.services.impl.ZjzhServiceImpl;

public class MainThread extends Thread {

	private static final Logger log = Logger.getLogger(MainThread.class);
	public MainThread()
	{
		log.log(Priority.INFO, "主线程启动");
		 init();
	}
	public void init()
	{
		new RecvThread().start();
		IZjzhService zjzhService = new ZjzhServiceImpl();
		zjzhService.doLogin();
		while(true)
		{
			if(SysContext.IS_START)
			{
				new GetRequestThread().start();
				new NoticeThread().start();
				new HeartThread().start();
				synchronized (SysContext.THREAD_LIST) {
					if(SysContext.THREAD_LIST.size() < SysContants.MAX_TASKNUM)
					{
						for(int i = 0; i < SysContants.MAX_TASKNUM; i++)
						{
							SendThread sendThread = new SendThread();
							SysContext.THREAD_LIST.add(sendThread);
							sendThread.start();
						}
					}
				}
				
				IReloadService reloadService = new ReloadServiceImpl();
				reloadService.reloadUnNoticeOrder();
				reloadService.reloadUnSendOrder();
				return;
			}
		}
		
	}
	
	public void run()
	{
		while(true)
		{
			if(SysContext.IS_START)
			{
				//上游服务连接成功
				synchronized (SysContext.THREAD_LIST) {
					log.log(Priority.INFO, "当前交易线程数【" + SysContext.THREAD_LIST.size() + "】");
					if(SysContext.THREAD_LIST.size() < SysContants.MAX_TASKNUM)
					{
						SendThread sendThread = new SendThread();
						SysContext.THREAD_LIST.add(sendThread);
						sendThread.start();
					}
				}
				try {
					Thread.sleep(300000); //5分钟监控一次线程状态
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
				}
				
			}else{
				try {
					log.log(Priority.INFO, "上游服务主动断开，3秒后重新连接");
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
				}
			}
		}
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		log.log(Priority.INFO, "主线程被销毁");
	}
}
